package com.clkj.sunhelp.mvp.jobdeal.jobwaittododetail.choosephotoandupdate;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;

import com.clkj.sunhelp.R;
import com.clkj.sunhelp.adapter.rv.RecycleViewOfChoosedPicAdapter;
import com.clkj.sunhelp.app.CustomApplication;
import com.clkj.sunhelp.bean.JobWaitToDoItem;
import com.clkj.sunhelp.common.Config;
import com.clkj.sunhelp.common.IntentKey;
import com.clkj.sunhelp.common.SharePreKey;
import com.clkj.sunhelp.mvp.base.BaseActivity;
import com.clkj.sunhelp.util.CommonUtil;
import com.clkj.sunhelp.util.ImageCompressUtil;
import com.clkj.sunhelp.util.LogUtil;
import com.clkj.sunhelp.util.ToastUtil;
import com.clkj.sunhelp.util.schedulers.SchedulerProvider;
import com.clkj.sunhelp.util.viewutil.DividerGridItemDecoration;
import com.jakewharton.rxbinding.view.RxView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/3/31.
 */

public class ActivityChoosePicAndUpdate extends BaseActivity implements ChoosePicAndUpdateContract.View{

    private TextView tvChoosePicFromGallery;
    private TextView tvChoosePicFromCamera;
    private TextView tvSubmitPic;
    private RecyclerView rvPics;


    private final int REQUEST_CODE_CAMERA = 1000;
    private final int REQUEST_CODE_GALLERY = 1001;


    RecycleViewOfChoosedPicAdapter mPicChoosedAdapter;
    private List<PhotoInfo> mPhotoList = new ArrayList<>();
    private List<File> fileList = new ArrayList<>();

    JobWaitToDoItem mJobWaitToDoItem;

    ChoosePicAndUpdatePresenter mPresenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_pic_and_update);
        initTitleWithRightTvOrIv(null,null,"选择图片提交",true,null,null);
        initData();
        assignView();
        initView();

        mPresenter = new ChoosePicAndUpdatePresenter(this, SchedulerProvider.getInstance(), CustomApplication.getInstance().getHttpService());
    }

    @Override
    public void initData() {
        mJobWaitToDoItem = (JobWaitToDoItem) getIntent().getSerializableExtra(IntentKey.INTENT_KEY_JOB_ITEM);
    }

    @Override
    public void assignView() {
        tvChoosePicFromGallery = (TextView) findViewById(R.id.tv_choose_pic_from_gallery);
        tvChoosePicFromCamera = (TextView) findViewById(R.id.tv_choose_pic_from_camera);
        tvSubmitPic = (TextView) findViewById(R.id.tv_submit_pic);
        rvPics = (RecyclerView) findViewById(R.id.rv_pics);
    }

    @Override
    public void initView() {
        GridLayoutManager mLayoutManager =  new GridLayoutManager(this,2);
        rvPics.setLayoutManager(mLayoutManager);
        rvPics.addItemDecoration(new DividerGridItemDecoration(this));
        mPicChoosedAdapter = new RecycleViewOfChoosedPicAdapter(mPhotoList,this);
        //mPicChoosedAdapter.setPicItemClickListener(new PicItemClickListenerImpl());
        rvPics.setAdapter(mPicChoosedAdapter);

        RxView.clicks(tvChoosePicFromGallery)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        FunctionConfig functionConfig = initGalleyFunctionConfig();
                        GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY, functionConfig, mOnHanlderResultCallback);

                    }
                });

        RxView.clicks(tvChoosePicFromCamera)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        FunctionConfig functionConfigNew = initGalleyFunctionConfig();

                        if (mPhotoList.size()< Config.UPLOAD_PIC_NUM_PER_TIME)
                        {
                            GalleryFinal.openCamera(REQUEST_CODE_CAMERA, functionConfigNew, mOnHanlderResultCallback);
                        }else{
                            ToastUtil.showShort(ActivityChoosePicAndUpdate.this, "最多上传"+ Config.UPLOAD_PIC_NUM_PER_TIME+"张图片");
                        }
                    }
                });

        RxView.clicks(tvSubmitPic)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mPhotoList.size()>0)
                        {
                            compressedPicAndUpload(mPhotoList);
                        }else {
                            ToastUtil.showShort(ActivityChoosePicAndUpdate.this,"请选择要提交的图片");
                        }
                    }
                });

    }


    //初始化图片选择functionconfig
    private FunctionConfig initGalleyFunctionConfig()
    {
        FunctionConfig.Builder functionConfigBuilder = new FunctionConfig.Builder();
        functionConfigBuilder.setMutiSelectMaxSize(5);
        functionConfigBuilder.setEnableCamera(true);
        functionConfigBuilder.setEnablePreview(true);
        functionConfigBuilder.setSelected(mPhotoList);//添加过滤集合
        return functionConfigBuilder.build();
    }

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int requestCode, List<PhotoInfo> resultList) {


            if (requestCode == REQUEST_CODE_GALLERY)
            {
                if (resultList != null) {
                    mPhotoList.clear();
                    mPhotoList.addAll(resultList);
                    mPicChoosedAdapter.notifyDataSetChanged();
                }
            }
            //如果是拍照的话，则直接添加
            if (requestCode == REQUEST_CODE_CAMERA)
            {
                if (resultList != null) {
                    mPhotoList.addAll(resultList);
                    mPicChoosedAdapter.notifyDataSetChanged();
                }
            }

        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(ActivityChoosePicAndUpdate.this, errorMsg, Toast.LENGTH_SHORT).show();
        }
    };

    private static final int HANDLER_TAG_COMPRESSED_PIC_SUCCESS = 1000;

    //处理图片压缩的handler
    Handler mCompressedFileHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case HANDLER_TAG_COMPRESSED_PIC_SUCCESS:

                    List<File> compressedPicList = (List<File>) msg.obj;
                    uploadPic(compressedPicList);

                    break;
            }
        }
    };

    //压缩图片并且上传
    private void compressedPicAndUpload(final List<PhotoInfo> choosedPhotoInfo){

        showProgressDialog(false,null);

        final List<File> compressedFileList = new ArrayList<>();

        Observable.from(choosedPhotoInfo)

                .map(new Func1<PhotoInfo, File>() {
                    @Override
                    public File call(PhotoInfo photoInfo) {
                        LogUtil.e("BeforeCompressFileSize:"+new File(photoInfo.getPhotoPath()).length() / 1024 + "k");

                        return ImageCompressUtil.compressLocalPic(photoInfo.getPhotoPath());
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<File>() {
                    @Override
                    public void call(File file) {
                        LogUtil.e("afterCompressFileSize:"+file.length() / 1024 + "k");

                        compressedFileList.add(file);

                        if (compressedFileList.size() == choosedPhotoInfo.size())
                        {
                            Message message = new Message();
                            message.what = HANDLER_TAG_COMPRESSED_PIC_SUCCESS;
                            message.obj = compressedFileList;
                            mCompressedFileHandler.sendMessage(message);
                        }
                    }
                });
    }

    @Override
    public void uploadPic(List<File> fileList) {
        mPresenter.uploadFile(mJobWaitToDoItem.getActivityName(),mJobWaitToDoItem.getActivityId(),mJobWaitToDoItem.getId(), (String) CommonUtil.getShareValue(SharePreKey.SP_KEY_USERID,""),fileList);
    }

    @Override
    public void onUploadPicSuccess() {
        ToastUtil.showShort(this,"上传成功");
        finish();
    }

    @Override
    public void onUploadPicError(String tip) {
        ToastUtil.showShort(this,tip);
    }

    @Override
    public void setPresenter(ChoosePicAndUpdateContract.Presenter presenter) {

    }

    @Override
    public void showLoading() {
        showProgressDialog(false,null);
    }

    @Override
    public void dismissLoading() {
        dismissProgressDialog();

    }
}
